package org.visionlibrary.image.geomtric.model;

import java.util.List;
import java.util.PriorityQueue;

import org.visionlibrary.image.geomtric.util.Pair;


public class Acumulator2d {

	private int[][] acumulator;
	private int width;
	private int height;

	public Acumulator2d(int width, int height) {
		this.acumulator = new int[width][height];
		this.height = height;
		this.width = width;
	}

	public void set(int x, int y) {
		set(x, y, 1);
	}

	public void set(Point2d point) {
		set(point.getXAsInt(), point.getYAsInt());
	}

	public void set(Point2d point, int value) {
		set(point.getXAsInt(), point.getYAsInt(), value);
	}

	public void set(int x, int y, int value) {
		this.acumulator[x][y] += value;
	}

	public int get(int x, int y) {
		return this.acumulator[x][y];
	}

	public int get(Point2d point) {
		return this.acumulator[point.getXAsInt()][point.getYAsInt()];
	}

	public void unSet(int x, int y) {
		if (get(x, y) > 0) {
			this.acumulator[x][y]--;
		}
	}

	public void unSet(Point2d point) {
		if (get(point.getXAsInt(), point.getYAsInt()) > 0) {
			this.acumulator[point.getXAsInt()][point.getYAsInt()]--;
		}
	}

	public int width() {
		return this.width;
	}

	public int height() {
		return this.height;
	}

	public void clear() {
		for (int i = 0; i < width; i++)
			java.util.Arrays.fill(acumulator[i], 0);
	}

	public static List<Pair<Integer, Integer>> getVotes(Acumulator2d acumulator, int threshold) {
		if (null == acumulator)
			throw new NullPointerException("Acumulator is null");
		if (threshold <= 0)
			throw new IllegalArgumentException("Threshold must be 1 or more");
		
		
		
		return null;
	}
	
	public static PriorityQueue<Cell2d<Integer, Integer, Integer>> getMaximas(
			Acumulator2d acumulator, int maximas) {

		if (null == acumulator)
			throw new NullPointerException("Acumulator is null");
		if (maximas <= 0)
			throw new IllegalArgumentException("Maximas must be 1 or more");

		Cell2d<Integer, Integer, Integer> cell = null;
		PriorityQueue<Cell2d<Integer, Integer, Integer>> queue = new PriorityQueue<Cell2d<Integer, Integer, Integer>>();

		for (int x = 0; x < acumulator.width; x++) {
			for (int y = 0; y < acumulator.height; y++) {
				int votes = acumulator.get(x, y);
				if (votes > 0) {
					cell = Cell2d.packInt(x, y, votes);
					queue.add(cell);
					if (queue.size() > maximas) {
						cell = queue.poll();
					}
				}
			}
		}
		
		return queue;
	}
}
